/* eslint-disable no-shadow */
/* eslint-disable react/no-array-index-key */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Layout, Tree, Row, Button, Divider, Spin, Modal, Input, message, Col } from 'antd';
import moment from 'moment';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Authorized from '@/utils/Authorized';
import styles from '@/utils/utils.less';
import TextOverFlow from '@/pages/components/TextOverFlow';
import DictCode from '../../components/DictCode';
import ServiceArea from './ServiceArea';

const { Sider, Content } = Layout;
const { TreeNode } = Tree;
const FormItem = Form.Item;
const { confirm } = Modal;
@connect(({ organmanage, loading }) => ({
  organmanage,
  loading: loading.effects['organmanage/fetchOrgList'],
  tableLoading: loading.effects['organmanage/fetchPageListByParentId'],
}))
@Form.create()
class List extends PureComponent {
  state = {
    autoExpandParent: true,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    // 获取字典值
    dispatch({
      type: 'organmanage/fetchDictList',
      payload: ['ORG_TYPE'],
    });
    this.orgList();
  }

  // 左侧列表
  orgList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'organmanage/fetchOrgList',
      payload: {},
      callback: parentId => {
        this.getList(parentId, 1, 10);
      },
    });
  };

  // 操作完之后，刷新左侧列表
  refreshLeftList = () => {
    const {
      organmanage: { expandedTreeKeys },
      dispatch,
    } = this.props;
    expandedTreeKeys.forEach(item => {
      dispatch({
        type: 'organmanage/fetchOrgListByParentId',
        payload: {
          parentId: item,
        },
      });
      // return true;
    });
  };

  // 左侧列表子级
  orgChildList = () => {
    const {
      dispatch,
      organmanage: { selectedTreeKeys, expandedTreeKeys },
    } = this.props;
    dispatch({
      type: 'organmanage/fetchOrgListByParentId',
      payload: {
        parentId: selectedTreeKeys[0],
      },
    });
    setTimeout(() => {
      this.onExpand(expandedTreeKeys);
    }, 1000);
  };

  // 右侧表格
  getList = (parentId, currentPage = 1, pageSize = 10) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'organmanage/fetchPageListByParentId',
      payload: {
        page: {
          currentPage,
          pageSizes: pageSize,
          orderby: '',
        },
        parentId,
      },
    });
  };

  onSelect = (selectedKeys, info) => {
    const { dispatch } = this.props;
    if (!selectedKeys.length) {
      return;
    }
    dispatch({
      type: 'organmanage/updateModalData',
      payload: {
        selectedTreeKeys: selectedKeys,
        corpId: info.node.props.dataRef.corpId,
        // orgId
      },
    });
    this.getList(selectedKeys[0], 1, 10);
  };

  onExpand = expandedTreeKeys => {
    const { dispatch } = this.props;
    dispatch({
      type: 'organmanage/updateModalData',
      payload: {
        expandedTreeKeys,
      },
    });
    this.setState({
      autoExpandParent: true,
    });
  };

  onLoadData = treeNode => {
    const { dispatch } = this.props;
    const parentId = treeNode.props.dataRef.key;
    return new Promise(resolve => {
      dispatch({
        type: 'organmanage/fetchOrgListByParentId',
        payload: {
          parentId,
        },
      });
      setTimeout(() => {
        resolve();
      }, 500);
    });
  };

  handleStandardTableChange = pagination => {
    const {
      organmanage: { selectedTreeKeys },
    } = this.props;

    this.getList(selectedTreeKeys[0], pagination.current, pagination.pageSize);
  };

  // 新增
  add = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'organmanage/updateModalData',
      payload: {
        isAdd: true,
        modifyData: {},
      },
    });
    this.getArealist();

    this.handleModalVisible(true);
  };

  handleModalVisible = visible => {
    const { dispatch } = this.props;
    dispatch({
      type: 'organmanage/updateModalData',
      payload: {
        addModVisible: visible, // 新增和修改公用一个visible属性
      },
    });
  };

  handleOk = () => {
    const {
      dispatch,
      form,
      organmanage: {
        isAdd,
        selectedTreeKeys,
        corpId,
        pageData: { pagination },
        modifyData,
      },
    } = this.props;
    form.validateFields((err, values) => {
      if (!err) {
        console.log('values', values);
        const areaIdList = [];
        if (values.areaId) {
          values.areaId.forEach(item => {
            areaIdList.push(item.key);
          });
        }

        if (isAdd) {
          dispatch({
            type: 'organmanage/insertOrgInfo',
            payload: {
              ...values,
              parentId: selectedTreeKeys[0],
              corpId,
              areaIdList: areaIdList.length ? areaIdList : undefined,
            },
            callback: res => {
              if (res) {
                message.success('新增成功');
                this.refreshLeftList();
                this.handleModalVisible(false);
                this.getList(selectedTreeKeys[0], pagination.current, pagination.pageSize);
              }
            },
          });
        } else {
          dispatch({
            type: 'organmanage/updateOrgInfo',
            payload: {
              ...values,
              parentId: selectedTreeKeys[0],
              corpId,
              orgId: modifyData.orgId,
              vno: modifyData.vno,
              areaIdList: areaIdList.length ? areaIdList : undefined,
            },
            callback: res => {
              if (res) {
                this.refreshLeftList();
                this.handleModalVisible(false);
                this.getList(selectedTreeKeys[0], pagination.current, pagination.pageSize);
              }
            },
          });
        }
      }
    });
  };

  handleCancel = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'organmanage/updateModalData',
      payload: {
        addModVisible: false, // 新增和修改公用一个visible属性
      },
    });
  };

  // 修改
  goUpdate = (orgId, orgType) => {
    const {
      dispatch,
      organmanage: { corpId },
    } = this.props;
    // this.getArealist();
    dispatch({
      type: 'organmanage/fetchAreaList',
      payload: { corpId },
      callback: res => {
        if (res) {
          dispatch({
            type: 'organmanage/fetchOrgById',
            payload: {
              orgId,
            },
          });
        }
      },
    });
    dispatch({
      type: 'organmanage/updateModalData',
      payload: {
        isAdd: false,
        areaShow: Number(orgType) === 2,
      },
    });

    this.handleModalVisible(true);
  };

  // 删除数据
  delList = orgId => {
    const {
      dispatch,
      organmanage: {
        selectedTreeKeys,
        pageData: { pagination },
      },
    } = this.props;
    confirm({
      title: '你确定要删除此条信息吗？',
      okText: '确定',
      icon: <ExclamationCircleOutlined />,
      okType: 'primary',
      cancelText: '取消',
      style: { top: 200 },
      onOk: () => {
        dispatch({
          type: 'organmanage/deleteOrg',
          payload: {
            orgId,
          },
          callback: res => {
            if (res) {
              // this.orgChildList();
              message.success('删除成功');
              this.refreshLeftList();
              // this.orgList();
              this.getList(selectedTreeKeys[0], pagination.current, pagination.pageSize);
            }
          },
        });
      },
    });
  };

  // 获取服务地区下拉项
  getArealist = () => {
    const {
      dispatch,
      organmanage: { corpId },
    } = this.props;
    dispatch({
      type: 'organmanage/fetchAreaList',
      payload: { corpId },
    });
  };

  // 选择服务地区
  orgTypeChange = value => {
    const { dispatch } = this.props;
    dispatch({
      type: 'organmanage/updateModalData',
      payload: {
        areaShow: Number(value) === 2,
      },
    });
  };

  render() {
    const { autoExpandParent } = this.state;
    const hei = window.screen.height;
    const {
      organmanage,
      loading,
      tableLoading,
      form: { getFieldDecorator },
      organmanage: { addModVisible, modifyData, isAdd, areaList, areaShow },
    } = this.props;
    const { treeData, selectedTreeKeys, pageData, expandedTreeKeys } = organmanage;
    const formItemLayout = {
      labelCol: {
        md: {
          span: 6,
        },
      },
      wrapperCol: {
        md: {
          span: 16,
        },
      },
    };
    const columns = [
      {
        title: '机构名称',
        dataIndex: 'name',
        width: 120,
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '机构类型',
        width: 120,
        dataIndex: 'orgTypeName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '所属机构',
        dataIndex: 'parentOrgName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '备注',
        dataIndex: 'remark',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '创建时间',
        width: 150,
        dataIndex: 'createTime',
        onCell: () => ({ style: { textAlign: 'center' } }),
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        render: text => moment(text).format('YYYY-MM-DD'),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        width: 120,
        onCell: () => ({ style: { textAlign: 'center' } }),
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        render: (text, record) => (
          <div>
            <Authorized authority="mgr:org:updateOrgInfo" noMatch={null}>
              <span
                style={{ color: '#1890FF', cursor: 'pointer' }}
                onClick={() => {
                  this.goUpdate(record.orgId, record.orgType);
                }}
              >
                修改
              </span>
              <Divider type="vertical" />
            </Authorized>
            <Authorized authority="mgr:org:deleteOrgById" noMatch={null}>
              <span
                style={{ color: '#1890FF', cursor: 'pointer' }}
                onClick={() => this.delList(record.orgId, record.parentId)}
              >
                删除
              </span>
            </Authorized>
          </div>
        ),
      },
    ];
    const renderTree = data =>
      data.map(item => {
        if (item.children) {
          return (
            <TreeNode
              {...item}
              dataRef={item}
              style={{
                width: '274px',
                whiteSpace: 'nowrap',
                overflow: 'hidden',
                textOverFlow: 'ellipsis',
              }}
            >
              {renderTree(item.children)}
            </TreeNode>
          );
        }
        return <TreeNode {...item} dataRef={item} />;
      });
    return (
      <PageHeaderWrapper>
        <div>
          <Spin spinning={loading}>
            <Layout>
              <div className={styles.setSider}>
                <Sider style={{ background: '#fff', width: 274, height: hei }}>
                  <div className={styles.setTree} style={{ height: hei }}>
                    <Tree
                      showLine
                      onSelect={this.onSelect}
                      loadData={this.onLoadData}
                      selectedKeys={selectedTreeKeys}
                      autoExpandParent={autoExpandParent}
                      expandedKeys={expandedTreeKeys}
                      onExpand={this.onExpand}
                    >
                      {renderTree(treeData)}
                    </Tree>
                  </div>
                </Sider>
              </div>
              <div className={styles.contentBody}>
                <Content>
                  <Row>
                    <Authorized authority="mgr:org:insertOrgInfo" noMatch={null}>
                      <Button type="primary" onClick={this.add} style={{ marginBottom: 16 }}>
                        <PlusOutlined />
                        新增
                      </Button>
                    </Authorized>
                  </Row>
                  <Form>
                    <Row>
                      <Col span={24}>
                        <StandardTable
                          loading={tableLoading}
                          data={pageData}
                          columns={columns}
                          rowKey="orgId"
                          rowSelection={null}
                          selectedRows={[]}
                          selectedRowKeys={[]}
                          onChange={this.handleStandardTableChange}
                        />
                      </Col>
                    </Row>
                  </Form>
                  <Modal
                    visible={addModVisible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                    title={isAdd ? '添加功能' : '修改功能'}
                    okText="确认"
                    destroyOnClose
                  >
                    <FormItem label="机构名称：" {...formItemLayout}>
                      {getFieldDecorator('name', {
                        rules: [
                          {
                            required: true,
                            message: `请输入机构名称`,
                          },
                        ],
                        initialValue: modifyData.name,
                      })(<Input placeholder="请输入" maxLength={20} />)}
                    </FormItem>
                    <FormItem label="机构类型：" {...formItemLayout}>
                      {getFieldDecorator('orgType', {
                        rules: [
                          {
                            required: true,
                            message: `请选择`,
                          },
                        ],
                        initialValue: modifyData.orgType,
                      })(
                        <DictCode
                          allowClear
                          showSearch
                          filterOption={(input, option) =>
                            option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                          }
                          dictType="ORG_TYPE"
                          style={{ width: '100%' }}
                          onChange={this.orgTypeChange}
                          disabled={Number(modifyData.orgType) === 1 || !isAdd}
                        />
                      )}
                    </FormItem>
                    {areaShow && (
                      <FormItem {...formItemLayout} label="服务地区">
                        {getFieldDecorator('areaId', {
                          rules: [
                            {
                              required: true,
                              message: '请选择服务地区！',
                            },
                          ],
                          initialValue: modifyData.areaList,
                        })(<ServiceArea data={areaList} />)}
                      </FormItem>
                    )}
                    <FormItem label="备注：" {...formItemLayout}>
                      {getFieldDecorator('remark', {
                        rules: [
                          {
                            required: false,
                            message: `请输入字数不超过200的备注！`,
                            max: 200,
                          },
                        ],
                        initialValue: modifyData.remark,
                      })(<Input placeholder="请输入" />)}
                    </FormItem>
                  </Modal>
                </Content>
              </div>
            </Layout>
          </Spin>
        </div>
      </PageHeaderWrapper>
    );
  }
}

export default List;
